const util = require('../../../utils/util.js');
const app = getApp();

Page({
  data: {
    canIUseGetUserProfile: false,
    phoneVisible: false,
    navUrl: '',
    isTcp: false, //协议
    code: '',
    projectName: '',
    logoUrl: 'https://platform-wxmall.oss-cn-beijing.aliyuncs.com/logo.png'
  },

  onLoad: function (options) {
    let that = this;
    that.setData({
      projectName: app.globalData.projectName
    })
    util.request('index/getTreaty', {
      type: 9
    }).then(res => {
      if (res.code === 0) {
        that.setData({
          logoUrl: res.data
        })
      }
    });
    if (wx.getUserProfile) {
      that.setData({
        canIUseGetUserProfile: true
      })
    }
    if (wx.getStorageSync("navUrl")) {
      that.setData({
        navUrl: wx.getStorageSync("navUrl")
      })
    } else {
      that.setData({
        navUrl: '/pages/index/index'
      })
    }
    wx.removeStorageSync('navUrl');

    //不在onLoad时候调用wx.login获取code，用户第一次登录会失败，暂时没查到原因
    wx.login({
      success: function (res) {
        if (res.code) {
          that.setData({
            code: res.code
          })
        }
      }
    });
  },
  noLogin: function () {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  goLogin: function () {
    let that = this;
    if (!that.checkIsTcp()) {
      return
    }
    wx.navigateTo({
      url: '/pages/auth/login/login',
    })
  },
  jump(e) {
    wx.navigateTo({
      url: '/pages/auth/richtext/richtext?id=' + e.currentTarget.dataset.type
    })
  },
  onTcp() {
    this.setData({
      isTcp: !this.data.isTcp
    })
  },
  checkIsTcp: function () {
    if (!this.data.isTcp) {
      util.showMsg('请先同意协议')
      return false
    }
    return true;
  },
  getPhoneNumber(e) {
    let that = this;
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      wx.login({
        success: function (r) {
          let code = r.code; //登录凭证
          util.request("auth/LoginByMaPhone", {
            userId: wx.getStorageSync('userId'),
            code: code,
            userInfo: e.detail
          }, 'POST', 'application/json').then(res => {
            if (res.code === 0) {
              if (that.data.navUrl && (that.data.navUrl == '/pages/index/index' || that.data.navUrl == '/pages/ucenter/index/index' || that.data.navUrl == '/pages/cart/cart')) {
                wx.switchTab({
                  url: that.data.navUrl,
                })
              } else if (that.data.navUrl) {
                wx.redirectTo({
                  url: that.data.navUrl
                })
              }
            } else {
              util.showMsg('请重新授')
            }
          }).catch(ex => {
            console.log(ex, "ex")
          });
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '为了获得更好的服务，请允许授权'
      })
    }
  },
  getUserProfile(e) {
    let that = this;
    if (!that.checkIsTcp()) {
      return
    }
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        //登录远程服务器
        if (that.data.code) {
          that.LoginByMa(res)
        } else {
          wx.login({
            success: function (resp) {
              if (resp.code) {
                that.setData({
                  code: resp.code
                })
                that.LoginByMa(res)
              }
            }
          });
        }
      }
    })
  },
  bindGetUserInfo: function (e) {
    let that = this;
    if (!that.checkIsTcp()) {
      return
    }
    if (e.detail.errMsg.indexOf("fail auth deny") > -1) {
      wx.showModal({
        title: '提示',
        content: '用户拒绝',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        }
      });
    } else {
      //登录远程服务器
      if (that.data.code) {
        that.LoginByMa(e.detail)
      } else {
        wx.login({
          success: function (res) {
            if (res.code) {
              that.setData({
                code: res.code
              })
              that.LoginByMa(e.detail)
            }
          }
        });
      }
    }
  },
  LoginByMa(userInfo) {
    let that = this;
    util.request('auth/LoginByMa', {
      code: that.data.code,
      userInfo: userInfo
    }, 'POST', 'application/json').then(res => {
      if (res.code === 0) {
        //存储用户信息
        wx.setStorageSync('userInfo', res.userInfo);
        wx.setStorageSync('token', res.token);
        wx.setStorageSync('userId', res.userId);
        if (res.userInfo.mobile) {
          if (that.data.navUrl && (that.data.navUrl === '/pages/index/index' || that.data.navUrl === '/pages/ucenter/index/index' || that.data.navUrl === '/pages/cart/cart')) {
            wx.switchTab({
              url: that.data.navUrl,
            })
          } else if (that.data.navUrl) {
            wx.redirectTo({
              url: that.data.navUrl,
            })
          }
        } else {
          that.setData({
            phoneVisible: true
          })
        }
      } else {
        util.showMsg(res.msg)
      }
    });
    //每个code只能使用一次
    that.setData({
      code: ""
    })
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  }
})
